#include "converter.h"
#include <QTcpSocket>
#include <QStringList>
#include <QDebug>

Converter::Converter(const QHostAddress &host, quint16 port, QObject *parent) :
    QObject(parent), m_state("device_not_connected"), m_host(host), m_port(port),
    m_status(IDLE)
{
    m_socket = new QTcpSocket(this);
    connect(m_socket, &QTcpSocket::connected, this, &Converter::connected);
    connect(m_socket, &QTcpSocket::readyRead, this, &Converter::readyRead);
}

QVariant Converter::state() const
{
    return m_state;
}

void Converter::setState(const QVariant &newState)
{
    m_socket->abort();
    m_socket->connectToHost(m_host, m_port);
    m_status = SET_STATE;
    m_newState = newState.toString();
}

void Converter::connected()
{
    qDebug() << "connected";
    switch (m_status) {
    case IDLE:
        qDebug() << "doing idle? wrong";
        break;
    case SET_STATE:
        qDebug() << "setting state" << m_newState;
        if (m_newState == "up" || m_newState == "down") {
            m_socket->write(m_newState.toLocal8Bit());
            m_status = GET_STATE;
        }
    case GET_STATE:
        qDebug() << "getting state";
        m_socket->write("status", 6);
        break;
    }
}

void Converter::readyRead()
{
    QByteArray answer = m_socket->readAll();
//    qDebug() << answer;
    QStringList entries = QString(answer).split('\n', QString::SkipEmptyParts);
    qDebug() << "answer" << entries;
    foreach (QString entry, entries) {
        if (entry.contains("psc")) {
            qDebug() << "device:" << entry;
        } else if (m_status == GET_STATE) {
            if (entry != "err") {
                m_state = entry;
                emit stateChanged(m_state);
            }
            m_status = IDLE;
            m_socket->disconnectFromHost();
        }
    }
}
